/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.pacs.controller.user;

import akka.actor.ActorRef;
import com.cxhd.pacs.DataConfig;
import com.cxhd.pacs.actor.ActorManager;
import com.cxhd.pacs.controller.service.PacsService;
import com.cxhd.pacs.model.FileDetail;
import com.cxhd.pacs.model.FileSystem;
import com.cxhd.pacs.services.HostService;
import com.cxhd.pacs.tools.DateUtil;
import com.cxhd.pacs.tools.DicomInfo;
import com.cxhd.pacs.tools.FileUtil;
import com.cxhd.pacs.tools.ImageRender;
import com.cxhd.pacs.tools.XmlRender;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.zeroturnaround.zip.ZipUtil;

/**
 *
 * @author 52461
 */
public class PacsCtrl extends Controller {

    PacsService ps = new PacsService();

    public void index() {
        render("/view/pacs/p_main.jsp");
    }

    //上传压缩文件解压并解析
    public void uploadDicom() {
        try {
            String fileName = getPara("fileName");
            String studyIuid = getPara("studyIuid");
            String hospitalCode = getPara("hospitalCode");
            String result = "false";
            if (ps.checkFile(studyIuid, fileName)) {
                String dicomPath = ps.saveDicom(studyIuid, fileName, this);
                if (dicomPath != null) {
                    System.out.println(dicomPath);
                    Map<String, String> info = DicomInfo.parseDicom(dicomPath);
                    System.out.println(info);
                    info.put("file_path", new File(dicomPath).getParent().replace("\\", "/") + "/");
                    info.put("dicom_path", dicomPath);
                    String pat_pk = ps.saveInfo(info, hospitalCode);
                    String study_pk = ps.saveStudy(info, pat_pk, hospitalCode);
                    String series_pk = ps.saveSeries(info, study_pk);
                    ps.saveSop(info, study_pk, series_pk);
                    ActorManager.getIntance().getActor("dicomToJpgActor").tell(info, ActorRef.noSender());
                    result = "true";
                }
            }
            renderText(result);

        } catch (Exception ex) {
            ex.printStackTrace();
            renderText("false");
        }

    }

    public void getList() {

        String sql = " select * ";
        String param = " from  pacs_study a left join pacs_pat b on a.pat_pk = b.pk  order by a.createtime desc  ";
        Page<Record> userPage = Db.paginate(getParaToInt("currentPage", 1),
                getParaToInt("pageSize", 10), sql, param);
        System.out.println(sql + param);
        renderJson(userPage);
    }

    public void saveOrder() {

        String sql = "select * from remote_order where pat_id='" + getPara("pat_id") + "' and study_iuid='" + getPara("study_iuid") + "' and status=0";
        Record re = Db.findFirst(sql);
        String result = "true";
        if (re != null) {
            result = "1";
        } else {
            Record info = new Record();
            String port = ps.getPort() + "";
            info.set("pat_id", getPara("pat_id"));
            info.set("pat_name", getPara("pat_name"));
            info.set("pat_pk", getPara("pat_pk"));
            info.set("study_iuid", getPara("study_iuid"));
            info.set("recvicer", getPara("recvicer"));
            info.set("sender", getPara("sender"));
            info.set("port", port);
            info.set("createtime", DateUtil.getDateEN());
            Db.save("remote_order", info);
            ps.createXml(this, port);

        }
        renderText(result);

    }
    public void saveOrderByPacs(){
      String sql = "select * from remote_order where pat_id='" + getPara("pat_id") + "' and study_iuid='" + getPara("study_iuid") + "' and recvicer='"+getPara("device_id")+"' and status=0";
        Record re = Db.findFirst(sql);
        String result = "true";
        if (re != null) {
            result = "false";
        } else {
            Record info = new Record();
            Record pat_info = Db.findFirst("select b.* from pacs_study a left join pacs_pat b on a.pat_pk=b.pk where a.pat_id = '"+getPara("pat_id")+"' and a.study_iuid = '"+getPara("study_iuid")+"'");
            if(pat_info!=null){
            String port = ps.getPort() + "";
            info.set("pat_id", getPara("pat_id"));
            info.set("pat_name", pat_info.get("pat_name"));
            info.set("pat_pk", pat_info.get("pk"));
            info.set("study_iuid", getPara("study_iuid"));
            info.set("recvicer", getPara("device_id"));
            info.set("sender", getPara("sender"));
            info.set("port", port);
            info.set("createtime", DateUtil.getDateEN());
            Db.save("remote_order", info);
            ps.createXml(this, port);
            }

        }
        renderText(result);
    }

    public void getOrder() {

        String sql = "select a.pk,b.study_datetime,c.pat_id,c.pat_name as name,c.pat_sex as sex,c.pat_age as age, a.port as imgURL,a.study_iuid, b.study_desc as `desc`, b.kvp as KVP,b.instituation,b.modality,b.study_device_id as studyDeviceID from "
                + " remote_order a left join pacs_study b using(study_iuid) left join pacs_pat c on b.pat_pk = c.pk where status=0 ";
        System.out.println(sql);
        List<Record> list = Db.find(sql);
        for (Record re : list) {
            if (re.getStr("sex").equalsIgnoreCase("F")) {
                re.set("sex", "女");
            } else {
                re.set("sex", "男");
            }
            //Db.update("update remote_order set status=1 where pk= " + re.get("pk"));
            re.set("status", "new");
            re.set("user", "");
            re.set("imgURL", "http://" + DataConfig.getInstance().getConfig().get("dicomServerUrl") + ":" + re.get("imgURL") + "/getImage.php");
        }
        renderJson(list);

    }

    public void updateOrderStatus() {

    }

    public void getDetail() {

        Record info = Db.findFirst("select a.pk, c.pat_name as name,c.pat_id ,c.pat_sex as sex,c.pat_age as age, a.port as imgURL,a.study_iuid, b.study_desc as `desc`,b.study_datetime, b.kvp as KVP,b.instituation,b.modality,b.study_device_id as studyDeviceID from  remote_order a left join pacs_study b using(study_iuid) left join pacs_pat c on b.pat_pk = c.pk where status=0 and a.study_iuid='" + getPara("study_iuid") + "' ");
        if (info.getStr("sex").equalsIgnoreCase("F")) {
            info.set("sex", "女");
        } else {
            info.set("sex", "男");
        }
        //Db.update("update remote_order set status=1 where pk= " + re.get("pk"));
        info.set("status", "new");
        info.set("user", "");
        info.set("imgURL", "http://" + DataConfig.getInstance().getConfig().get("dicomServerUrl") + ":" + info.get("imgURL") + "/getImage.php");

        List<Record> series = Db.find("select series_iuid as siuid, series_desc as `desc`,width,height,pixs,wc AS WC,ww as WW  from pacs_series where study_iuid='" + getPara("study_iuid") + "'");
        System.out.println("select series_iuid as siuid, series_desc as `desc`,width,height,pixs,wc AS WC,ww as WW  from pacs_series where study_iuid='" + getPara("study_iuid") + "'");
        for (Record re : series) {

            List<Record> sops = Db.find("select sop_iuid ,data1 as position,data2 as `index` from pacs_sop where series_iuid='" + re.getStr("siuid") + "' order by (data2+0) " );
//            List<String> sop_list = new ArrayList<String>();
//            for (Record sop : sops) {
//                sop_list.add(sop.getStr("sop_iuid"));
//            }
            re.set("sops", sops);

        }
        Record map = Db.findFirst("select * from pacs_study a left join remote_order b using(study_iuid) where study_iuid='" + getPara("study_iuid") + "'");
        ActorManager.getIntance().getActor("startDicomExeActor").tell(map, ActorRef.noSender());

        Map<String, Object> reuslt = new HashMap<String, Object>();
        reuslt.put("info", info);
        reuslt.put("series", series);
        renderJson(reuslt);
    }

    public void getImage() {
        String study_iuid = getPara("study_iuid");
        Record re = Db.findFirst("select * from pacs_sop a left join pacs_study b using(study_iuid) where a.study_iuid='" + study_iuid + "'");
        System.out.println("select * from pacs_sop a left join pacs_study b using(study_iuid) where a.study_iuid='" + study_iuid + "'");
        if (re != null) {
            String path = re.getStr("file_path") + "image/" + re.getStr("sop_iuid") + ".jpg";
            render(new ImageRender(new File(path), ""));
        }

    }

    public void getSopXml() throws IOException {
        String sop_iuid = getPara("sop_iuid");
        Record re = Db.findFirst("select * from pacs_sop a left join pacs_study b using(study_iuid) where a.sop_iuid='" + sop_iuid + "'");
        System.out.println("select * from pacs_sop a left join pacs_study b using(study_iuid) where a.sop_iuid='" + sop_iuid + "'");
        if (re != null) {
            String path = re.getStr("file_path") + "xml/" + re.getStr("sop_iuid") + ".xml";
            SAXReader reader = new SAXReader();

            StringReader in = new StringReader(FileUtil.outWriter(path, "gbk"));
            Document doc = null;
            try {
                doc = reader.read(in);
            } catch (DocumentException ex) {
                Logger.getLogger(PacsCtrl.class.getName()).log(Level.SEVERE, null, ex);
            }
            OutputFormat formater = OutputFormat.createPrettyPrint();
            formater.setEncoding("utf-8");
            StringWriter out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, formater);

            writer.write(doc);
            setAttr("content", out.toString());
            render("/view/pacs/viewXml.jsp");
            //render(new XmlRender(path,"gbk"));
        }

    }

    public void saveVoice() {

        String study_iuid = getPara("study_iuid");
        String fileName = getPara("fileName");
        String result = "false";
        System.out.println(study_iuid + "===  " + fileName);
        if (study_iuid != null && !study_iuid.equalsIgnoreCase("")) {
            Record re = Db.findFirst("select * from pacs_study where study_iuid='" + study_iuid + "'");
            String path = re.getStr("file_path") + "voice/";
            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }
            if (ps.saveVoice(path + fileName, this)) {
                Db.update("update pacs_study set voice_status =1 where study_iuid='" + study_iuid + "' ");
                result = "true";
            }
        }
        renderText(result);

    }
}
